package com.dao.impl;

import com.dao.EmployeesDao;
import com.entity.Employees;
import com.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/*
*
*@author XCH
*@date2025 - 02 - 26
*
*/
    public class EmployeesDaoImplDButils implements EmployeesDao {
    QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());

    @Override
    public List<Employees> selectByPage(int currentPage, int pageSize) {
        String sql = "select id, name, age, phone, sta_pos, add_time, update_time from staffs limit ?, ?";
        Object[] params = {(currentPage - 1) * pageSize, pageSize};
        try {
            return qr.query(sql, params, new BeanListHandler<Employees>(Employees.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int insert(Employees employees) {
        String sql = "insert into staffs(name, age, phone, sta_pos) values(?,?,?,?)";
        Object[] params = {employees.getName(), employees.getAge(), employees.getPhone(), employees.getSta_pos()};
        try {
            int result = qr.update(sql, params);
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int delete(String id) {
        String sql = "delete from staffs where id = ?";
        Object[] params = {id};
        try {
            return qr.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int update(Employees employees) {
        String sql = "update staffs set name = ?, age = ?, phone = ?, sta_pos = ? where id = ?";
        Object[] params = {employees.getName(), employees.getAge(), employees.getPhone(), employees.getSta_pos(), employees.getId()};
        try {
            return qr.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
